<template>
  <div class="my-bookings-page">
    <h2>我的订单</h2>

    <section class="all-bookings-section">
      <h3>所有预约订单</h3>
      <div class="filter-controls">
        <label for="statusFilter">筛选订单状态:</label>
        <select id="statusFilter" v-model="selectedStatusFilter">
          <option value="all">所有状态</option>
          <option value="0">已预约 (待支付)</option>
          <option value="1">已支付</option>
          <option value="2">已退款</option>
          <option value="3">订单失效</option>
          <option value="4">退款待审核</option>
        </select>
      </div>
      <div v-if="filteredBookings.length === 0" class="no-bookings">
        暂无符合条件的预约订单。
      </div>
      <ul v-else class="booking-list">
        <li v-for="booking in sortedBookings" :key="booking.orderId" class="booking-item" :class="getBookingStatusClass(booking)">
          <div class="booking-details">
            <p><strong>订单ID:</strong> {{ booking.orderId }}</p>
            <p><strong>会议室:</strong> {{ booking.roomName }}</p>
            <p><strong>时间:</strong> {{ formatDateTime(booking.startTime) }} - {{ formatDateTime(booking.endTime) }}</p>
            <p><strong>总金额:</strong> ¥{{ booking.totalFee }}</p>
            <p><strong>订单状态:</strong> <span :class="['status-tag', getBookingStatusClass(booking)]">{{ getBookingStatusText(booking) }}</span></p>
          </div>
          <div class="booking-actions">
            <button
              @click="viewBookingDetails(booking.orderId)"
              class="view-details-button"
            >
              查看详情
            </button>
            <button
              v-if="canCancel(booking)"
              @click="handleCancelBooking(booking.orderId)"
              class="cancel-button"
            >
              取消订单
            </button>
          </div>
        </li>
      </ul>
    </section>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { getOrdersByUserId } from '@/apis/orders';
import { useUserStore } from '@/stores/user'; // Import user store

const router = useRouter();
const allBookings = ref([]);
const userStore = useUserStore(); // Initialize user store
const userId = computed(() => userStore.user?.id); // Get user ID from store
const selectedStatusFilter = ref('all'); // 'all' for all statuses, or a number for specific status

// Helper to parse date strings
const parseDateTime = (dtString) => new Date(dtString); // ISO 8601 format from API

const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return '';
  const date = new Date(dateTimeString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  });
};

// Determine booking status text based on paymentStatus
const getBookingStatusText = (booking) => {
  switch (booking.paymentStatus) {
    case 0: return '已预约 (待支付)';
    case 1: return '已支付';
    case 2: return '已退款';
    case 3: return '订单失效';
    case 4: return '退款待审核';
    default: return '未知状态';
  }
};

// Determine booking status class for styling
const getBookingStatusClass = (booking) => {
  switch (booking.paymentStatus) {
    case 0: return 'status-pending-payment'; // 已预约 (待支付)
    case 1: return 'status-completed'; // 已支付 (assuming completed or active)
    case 2: return 'status-cancelled'; // 已退款
    case 3: return 'status-invalid'; // 订单失效
    case 4: return 'status-pending-refund'; // 退款待审核
    default: return '';
  }
};

// Check if an order can be cancelled (simplified for now, based on paymentStatus)
const canCancel = (booking) => {
  // Only allow cancellation if the order is '已支付' (1) and not already '退款待审核' (4) or '已退款' (2)
  return booking.paymentStatus === 1;
};

// Filter bookings based on selected status
const filteredBookings = computed(() => {
  if (selectedStatusFilter.value === 'all') {
    return allBookings.value;
  }
  return allBookings.value.filter(booking => booking.paymentStatus === parseInt(selectedStatusFilter.value));
});

// Sort bookings: prioritize by status, then by start time
const sortedBookings = computed(() => {
  const orderMap = {
    0: 1, // 已预约 (待支付) - highest priority
    4: 2, // 退款待审核
    1: 3, // 已支付
    2: 4, // 已退款
    3: 5, // 订单失效
  };

  return [...filteredBookings.value].sort((a, b) => {
    const statusOrderA = orderMap[a.paymentStatus] || 99; // Unknown status last
    const statusOrderB = orderMap[b.paymentStatus] || 99;

    if (statusOrderA !== statusOrderB) {
      return statusOrderA - statusOrderB;
    }

    // For same status, sort by start time (descending for upcoming, ascending for past)
    const startTimeA = parseDateTime(a.startTime);
    const startTimeB = parseDateTime(b.startTime);
    return startTimeB.getTime() - startTimeA.getTime(); // Newest first for same status
  });
});

// Handle cancel booking
const viewBookingDetails = (orderId) => {
  router.push({ name: 'BookingDetails', params: { id: orderId } });
};

const handleCancelBooking = (orderId) => {
  router.push({ name: 'CancelBooking', query: { orderId: orderId } });
};

const fetchBookings = async () => {
  if (!userId.value) {
    console.error('User ID is not available.');
    allBookings.value = [];
    return;
  }
  try {
    const response = await getOrdersByUserId(userId.value);
    if (response.code === 200 && response.data) {
      allBookings.value = response.data;
    } else {
      console.error('Failed to fetch bookings:', response.msg);
      allBookings.value = [];
    }
  } catch (error) {
    console.error('Failed to fetch bookings:', error);
    allBookings.value = [];
  }
};

onMounted(fetchBookings);
</script>

<style scoped>
.my-bookings-page {
  padding: 2rem;
  max-width: 900px;
  margin: 0 auto;
  font-family: 'Arial', sans-serif;
}

h2 {
  color: #333;
  text-align: center;
  margin-bottom: 2rem;
}

.all-bookings-section {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 1.5rem;
  margin-bottom: 2rem;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

h3 {
  color: #0056b3;
  margin-top: 0;
  margin-bottom: 1rem;
  border-bottom: 2px solid #eee;
  padding-bottom: 0.5rem;
}

.no-bookings {
  color: #666;
  text-align: center;
  padding: 1rem;
  background-color: #e9e9e9;
  border-radius: 4px;
}

.booking-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.booking-item {
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 6px;
  padding: 1rem;
  margin-bottom: 1rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 1rem;
}

.booking-details {
  flex-grow: 1;
}

.booking-item p {
  margin: 0.2rem 0;
  color: #555;
  font-size: 0.95rem;
}

.booking-item p strong {
  color: #333;
}

.status-tag {
  display: inline-block;
  padding: 0.3em 0.6em;
  border-radius: 4px;
  font-size: 0.85em;
  font-weight: bold;
  color: #fff;
}

.status-completed { background-color: #28a745; } /* Green */
.status-upcoming { background-color: #007bff; } /* Blue */
.status-in-progress { background-color: #ffc107; color: #333; } /* Yellow */
.status-pending-payment { background-color: #dc3545; } /* Red */
.status-cancelled { background-color: #6c757d; } /* Gray */

.cancel-button {
  padding: 0.6rem 1.2rem;
  background-color: #dc3545;
  color: #fff;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: background-color 0.3s ease;
}

.cancel-button:hover {
  background-color: #c82333;
}

.view-details-button {
  padding: 0.6rem 1.2rem;
  background-color: #007bff;
  color: #fff;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: background-color 0.3s ease;
  margin-right: 0.5rem; /* Add some spacing if there are other buttons */
}

.view-details-button:hover {
  background-color: #0056b3;
}

.filter-controls {
  margin-bottom: 1.5rem;
  display: flex;
  align-items: center;
  gap: 10px;
}

.filter-controls label {
  font-weight: bold;
  color: #555;
}

.filter-controls select {
  padding: 8px 12px;
  border: 1px solid #ccc;
  border-radius: 5px;
  font-size: 1rem;
  cursor: pointer;
  background-color: #fff;
}

.filter-controls select:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.25);
}

/* New status classes */
.status-invalid { background-color: #6c757d; } /* Gray for invalid/inactive */
.status-pending-refund { background-color: #ff9800; } /* Orange for pending refund */
</style>
